package com.jblv.frame.config;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.Properties;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ConfigCenterProperties
 * @projectName jblv-frame
 * @packageName com.jblv.frame.config
 * @description TODO
 * @date Create at 2020/9/7 17:32
 * @since jdk1.8
 */

public class ConfigCenterProperties implements FactoryBean<Properties>, InitializingBean
{
    private static boolean singleton = true;
    private static Properties properties;

    public static Properties getProperties() {
        if (!ConfigCenterProperties.singleton) {
            return ConfigCenterProperties.properties = ConfigPropertiesSourceLoader.build().getProperties();
        }
        if (ConfigCenterProperties.properties != null) {
            return ConfigCenterProperties.properties;
        }
        synchronized (ConfigCenterProperties.class) {
            if (ConfigCenterProperties.properties != null) {
                return ConfigCenterProperties.properties;
            }
            return ConfigCenterProperties.properties = ConfigPropertiesSourceLoader.build().getProperties();
        }
    }

    public static String getProperty(final String key) {
        return getProperties().getProperty(key);
    }

    public static String getProperty(final String key, final String defaultValue) {
        return getProperties().getProperty(key, defaultValue);
    }

    @Override
    public Properties getObject() throws Exception {
        if (!ConfigCenterProperties.singleton) {
            ConfigCenterProperties.properties = getProperties();
        }
        return ConfigCenterProperties.properties;
    }

    @Override
    public Class<?> getObjectType() {
        return Properties.class;
    }

    @Override
    public boolean isSingleton() {
        return ConfigCenterProperties.singleton;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (ConfigCenterProperties.singleton) {
            ConfigCenterProperties.properties = getProperties();
            //LoggerAdapterFactory.init(getProperties());// 日志更新级别
        }
    }

    static {
        ConfigCenterProperties.singleton = true;
    }
}